package cn.lee.demo.receiver;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.telephony.SmsManager;
import android.telephony.SmsMessage;
import android.util.Log;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by IntelliJ IDEA.
 * User: Lee
 * Date: 12-4-24
 * Time: 下午4:21
 */
public class SmsReceiver extends BroadcastReceiver {
    private static final String TAG="Cloud-Manager";
    public static final String SMS_ACTION = "android.provider.Telephony.SMS_SEND";
    public SmsReceiver() {
        Log.v(TAG, "SmsRecevier create");
    }
    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getAction().equals(SMS_ACTION)) {
            Log.v(TAG, "SmsRecevier onReceive");
        }
        Log.v(TAG, "SmsRecevier onReceive");
        Object[] pdus = (Object[]) intent.getExtras().get("pdus");
        if (pdus != null && pdus.length > 0) {
            SmsMessage[] messages = new SmsMessage[pdus.length];
            for (int i = 0; i < pdus.length; i++) {
                byte[] pdu = (byte[]) pdus[i];
                messages[i] = SmsMessage.createFromPdu(pdu);
            }
            for (SmsMessage message : messages) {
                String content = message.getMessageBody();// 得到短信内容
                String sender = message.getOriginatingAddress();// 得到发信息的号码
                Log.e(TAG, "此号码为:"+sender);
                if (sender.equals("5556")) {
                    abortBroadcast();// 中止发送
                    Log.e(TAG, "此号码为黑名单号码，已拦截!");
                }
//                Date date = new Date(message.getTimestampMillis());
//                SimpleDateFormat format = new SimpleDateFormat(
//                        "yyyy-MM-dd HH:mm:ss");
//                String sendContent = format.format(date) + ":" + sender + "--"
//                        + content;
//                SmsManager smsManager = SmsManager.getDefault();// 发信息时需要的
//                smsManager.sendTextMessage("", null, sendContent, null,
//                        null);// 转发给
//                Log.v(TAG, sendContent);
            }
            abortBroadcast();////终止此条广播
        }
    }
}
